<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\Config;
use app\model\Country;
use app\model\GlobalArea;
use app\model\HkArea;
use app\model\Store;
use app\model\Subway;
use app\tool\GpsUtils;
use app\tool\Http;
use think\db\Query;
use think\response\Json;

class CommonController extends BaseController
{
	protected $baidu_ak;
	protected $gaode_ak;
	
	
	/**
	 * 获取国家信息
	 * @return void
	 */
	function get_country()
	{
		$rows = GlobalArea::with([
			'class' => function (Query $query) {
				$query->order(['first' => 'asc'])->with(['class' => function (Query $query) {
					$query->order(['first' => 'asc']);
				}]);
			}
		])
			->where(['pid' => 0])
			->select();
		writeJson($rows);
	}
	
	/**
	 * 地铁信息
	 * @return Json
	 */
	function subway()
	{
		$rows = Subway::with(['class' => function (Query $query) {
			$query->with(['class']);
		}])->where(['pid' => 0])->select();
		writeJson($rows);
	}
	
	/**
	 * 香港地区
	 * @return Json
	 */
	function hk_area()
	{
		$subway = Subway::with(['class' => function (Query $query) {
			$query->with(['class']);
		}])->where(['pid' => 0])->find();
		$area = HkArea::with(['class' => function (Query $query) {
			$query->with(['class']);
		}])->where(['pid' => 0])->select();
		$area[1] = $subway;
		writeJson($area);
	}
	

	
	/**
	 * 小区
	 * @param $query
	 * @param $city
	 * @param int $page
	 * @return Json
	 */
	function region($query, $city, int $page = 1)
	{
		$this->baidu_ak = Config::getFieldByName('baidu_ak', 'value');
		$query = !empty($query) ? $query : '住宅区';
		$page -= 1;
		$url = 'https://api.map.baidu.com/place/v2/search?scope=2&page_size=' . $this->page_rows . '&page_num=' . $page . '&query=' . $query . '&tag=房地产&region=' . $city . '&output=json&ak=' . $this->baidu_ak;
		$res = http_request($url);
		$res = json_decode($res);
		if ($res->status != 0) {
			writeJson(0, $res->message);
		}
		writeJson($res->results);
	}
	
	/**
	 * 逆地理编码
	 * gong
	 * @param string $location
	 * @return Json
	 */
	function regeo(string $location)
	{
		$this->gaode_ak = Config::getFieldByName('gaode_ak', 'value');
		
		$res = Http::get('https://restapi.amap.com/v3/geocode/regeo', ['key' => $this->gaode_ak, 'location' => $location]);
		$res = json_decode($res);
		$res = $res->regeocode;
		writeJson($res);
	}
	
	function geo(string $address)
	{
		$this->gaode_ak = Config::getFieldByName('gaode_ak', 'value');
		$res = Http::get('https://restapi.amap.com/v3/geocode/geo', ['key' => $this->gaode_ak, 'address' => $address]);
		$res = json_decode($res);
		$res = $res->regeocode;
		writeJson($res);
	}
	
	/**
	 * 坐标转换
	 * @param float $lng
	 * @param float $lat
	 * @param $from //gcj02 bd09 wgs84
	 * @param $to //gcj02 bd09 wgs84
	 * @return Json
	 */
	function convert(float $lng, float $lat, $from, $to)
	{
		
		switch ($from) {
			case 'gcj02':
				switch ($to) {
					case 'bd09':
						$res = GpsUtils::gcj02ToBd09($lng, $lat);
						break;
					case 'wgs84':
						$res = GpsUtils::gcj02ToWgs84($lng, $lat);
						break;
					default:
						writeJson(0, 'to参数错误');
				}
				break;
			case 'bd09':
				switch ($to) {
					case 'gcj02':
						$res = GpsUtils::bd09ToGcj02($lng, $lat);
						break;
					case 'wgs84':
						$res = GpsUtils::bd09ToWgs84($lng, $lat);
						break;
					default:
						writeJson(0, 'to参数错误');
				}
				break;
			case 'wgs84':
				switch ($to) {
					case 'gcj02':
						$res = GpsUtils::wgs84ToGcj02($lng, $lat);
						break;
					case 'bd09':
						$res = GpsUtils::wgs84ToBd09($lng, $lat);
						break;
					default:
						writeJson(0, 'to参数错误');
				}
				break;
			default:
				writeJson(0, 'from参数错误');
		}
		writeJson(['lng' => $res[0], 'lat' => $res[1]]);
	}
	
	/**
	 * 周边范围
	 * @param float $lng
	 * @param float $lat
	 * @param int $page
	 * @param string $keyword
	 * @param int $distance
	 * @return Json
	 */
	function around(float $lng, float $lat, int $page, string $keyword, int $distance)
	{
//        $rows = Http::get('https://restapi.amap.com/v5/place/around',[
//            'key'=>$this->gaode_ak,
//            'keywords'=>$keyword,
//            'location'=>$lng.','.$lat,
//            'radius'=>5000,
//            'sortrule'=>'distance',
//            'page_size'=>15,
//            'page_num'=>$page,
//            'show_fields'=>'children,business,photos',
//        ]);
//        $rows = json_decode($rows);
//        if ($rows->status!='1'){
//            return write(400,$rows->info);
//        }
//        return write(200,'ok',$rows->pois);
		
		$rows = Store::field("*,(6371 * acos (cos ( radians($lat) ) * cos( radians( latitude ) ) * cos( radians(longitude) - radians( $lng ) ) +
		sin ( radians( $lat ) ) * sin( radians( latitude ) ))) AS distance")
			->whereLike('type', '%' . $keyword . '%')
			->page($page, $this->page_rows)
			->filter(function ($data) use ($lat, $lng) {
				if (empty($lat) || empty($lng)) {
					$data->distance_text = '';
				} else {
					if ($data->distance == 0) {
						$data->distance_text = '0m';
					} elseif (0 < $data->distance && $data->distance < 1) {
						$data->distance_text = bcmul((string)$data->distance, '1000') . 'm';
					} else {
						$data->distance_text = bcmul((string)$data->distance, '1', 1) . 'km';
					}
				}
//				list($Wgs84lng, $Wgs84lat) = GpsUtils::gcj02ToWgs84((float)$data->longitude, (float)$data->latitude);
//				$data->longitude = $Wgs84lng;
//				$data->latitude = $Wgs84lat;
				
			})
			->having("distance<=$distance")
			->order(['distance' => 'asc'])
			->group('title')
			->select();
		
		writeJson($rows);
	}
	
	/**
	 * 获取区域
	 * @param float $lat
	 * @param float $lng
	 * @return Json
	 */
	function get_area(float $lat, float $lng)
	{
		$rows = HkArea::where([['top', '>=', $lat], ['bottom', '<=', $lat], ['left', '<=', $lng], ['right', '>=', $lng]])->select();
		writeJson($rows);
	}
	
	
}
